package org.kfish.framework.helper;

import java.lang.annotation.Annotation;
import java.util.HashSet;
import java.util.Set;

import org.kfish.framework.annotation.Bean;
import org.kfish.framework.annotation.Controller;
import org.kfish.framework.annotation.Service;
import org.kfish.framework.config.EmbeddedConfigCustomizer;
import org.kfish.framework.util.ClassUtil;

/**
 * 类操作 helper
 * 
 * @author CK
 *
 */
public class ClassHelper {

	/**
	 * 定义存放类的集合
	 */
	private static final Set<Class<?>> CLASS_SET;

	static {
	
		String basePackage = ConfigHelper.getAppBasePackage();
		CLASS_SET = ClassUtil.getClassSet(basePackage);
	}

	/**
	 * 获取应用包名下所有的类
	 */
	public static Set<Class<?>> getClassSet() {
		return CLASS_SET;
	}

	/**
	 * 获取应用包名下所有的Service类
	 * 
	 * @return
	 */
	public static Set<Class<?>> getServiceClassSet() {

		Set<Class<?>> classSet = new HashSet<>();

		for (Class<?> cls : CLASS_SET) {

			if (cls.isAnnotationPresent(Service.class)) {
				classSet.add(cls);
			}

		}
		return classSet;
	}
	/**
	 * 获取应用包名下所有的Controller类
	 * 
	 * @return
	 */
	public static Set<Class<?>> getControllerClassSet() {
		Set<Class<?>> classSet = new HashSet<>();
		for (Class<?> cls : CLASS_SET) {

			if (cls.isAnnotationPresent(Controller.class)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}

	/**
	 * 获取含有@bean注解的类
	 * @return
	 */
	private static Set<Class<?>> getBeanSet(){
		Set<Class<?>> classSet = new HashSet<>();
		for (Class<?> cls : CLASS_SET) {

			if (cls.isAnnotationPresent(Bean.class)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
	
	
	/**
	 * 获取所有的Bean类（包含Service 、 Controller）
	 * @return
	 */
	public static Set<Class<?>> getBeanClassSet(){
		Set<Class<?>> beanClassSet = new HashSet<>();
		beanClassSet.addAll(getServiceClassSet());
		beanClassSet.addAll(getControllerClassSet());
		beanClassSet.addAll(getBeanSet());
		return beanClassSet;
	}
	/**
	 * 获取应用包名下具体父类（或接口）的所有子类（或实现类）
	 * @param superClass
	 * @return
	 */
	public static Set<Class<?>> getClassSetBySuper(Class<?> superClass){
		Set<Class<?>> classSet = new HashSet<Class<?>>();
		for(Class<?> cls:CLASS_SET){
			//找出其子类或实现类
			if(superClass.isAssignableFrom(cls)){
				classSet.add(cls);
			}
		}		
		return classSet;
	}
	/**
	 * 通过获取带有指定注解的类
	 * @param annotationClass
	 * @return
	 */
	public static Set<Class<?>> getClassSetByAnnotation(Class<? extends Annotation> annotationClass){
		Set<Class<?>> classSet = new HashSet<>();
		for (Class<?> cls : CLASS_SET) {
			if (cls.isAnnotationPresent(annotationClass)) {
				classSet.add(cls);
			}
		}
		return classSet;
	}
}
